program Collision;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  SampleCommon,
  DIrr in '..\..\DSource\DIrr.pas',
  DIrr.Line3D in '..\..\DSource\DIrr.Line3D.pas',
  DIrr.GUI in '..\..\DSource\DIrr.GUI.pas',
  DIrr.Color in '..\..\DSource\DIrr.Color.pas',
  DIrr.Rect in '..\..\DSource\DIrr.Rect.pas',
  DIrr.Event in '..\..\DSource\DIrr.Event.pas',
  DIrr.Vector2D in '..\..\DSource\DIrr.Vector2D.pas',
  DIrr.Vector3D in '..\..\DSource\DIrr.Vector3D.pas',
  DIrr.Video in '..\..\DSource\DIrr.Video.pas',
  DIrr.Base in '..\..\DSource\DIrr.Base.pas',
  DIrr.Types in '..\..\DSource\DIrr.Types.pas',
  DIrr.Scene in '..\..\DSource\DIrr.Scene.pas',
  DIrr.Structs in '..\..\DSource\DIrr.Structs.pas',
  DIrr.Matrix4 in '..\..\DSource\DIrr.Matrix4.pas',
  DIrr.Texture in '..\..\DSource\DIrr.Texture.pas',
  DIrr.Collections in '..\..\DSource\DIrr.Collections.pas',
  DIrr.Consts in '..\..\DSource\DIrr.Consts.pas',
  DIrr.Plane3D in '..\..\DSource\DIrr.Plane3D.pas',
  DIrr.Aabbox3D in '..\..\DSource\DIrr.Aabbox3D.pas',
  DIrr.Dimension2D in '..\..\DSource\DIrr.Dimension2D.pas',
  DIrr.Math in '..\..\DSource\DIrr.Math.pas',
  DIrr.IO in '..\..\DSource\DIrr.IO.pas',
  DIrr.Triangle3D in '..\..\DSource\DIrr.Triangle3D.pas';

const
    // I use this ISceneNode ID to indicate a scene node that is
    // not pickable by getSceneNodeAndCollisionPointFromRay()
    ID_IsNotPickable        = 0;

    // I use this flag in ISceneNode IDs to indicate that the
    // scene node can be picked by ray selection.
    IDFlag_IsPickable       = 1;

    // I use this flag in ISceneNode IDs to indicate that the
    // scene node can be highlighted.  In this example, the
    // homonids can be highlighted, but the level mesh can't.
    IDFlag_IsHighlightable  = 2;

var
  DriverType: E_DRIVER_TYPE;
  Device: TIrrlichtDevice;
  Driver: TVideoDriver;
  Smgr: TSceneManager;
  Q3levelmesh: TAnimatedMesh;
  Q3Node: TMeshSceneNode;
  Selector: TTriangleSelector;
  Camera: TCameraSceneNode;
  Anim: TSceneNodeAnimator;
  Bill: TBillboardSceneNode;
  Node: TAnimatedMeshSceneNode;
  Material: SMaterial;
  Light: TLightSceneNode;
  HighlightedSceneNode: TSceneNode;
  CollMan: TSceneCollisionManager;
  LastFPS: Integer;
  Ray: TLine3DF;
  // Tracks the current intersection point with the level or a mesh
  InterSection, TmpVec: TVector3DF;
	// Used to show with triangle has been hit
  HitTriangle: TTriangle3DF;
  SelectedSceneNode: TSceneNode;
  Matrix4: TMatrix4F;
  FPS: Integer;
  S: String;
  MaterialPtr: PMaterial;
begin
  try
    { TODO -oUser -cConsole Main : Insert code here }
    DriverType := DriverChoiceConsole;
    if DriverType = EDT_COUNT then
    begin
      ExitCode := 1;
      Exit;
    end;

    // create device and exit if creation failed
    Device := createDevice(DriverType, [640, 480], 16);
    if Device = nil then
    begin
      ExitCode := 1;   // could not create selected driver.
      Exit;
    end;

    Driver := Device.GetVideoDriver;
    Smgr := Device.GetSceneManager;

    Device.GetFileSystem.AddFileArchive('..\..\media\map-20kdm2.pk3');

    Q3levelmesh := Smgr.GetMesh('20kdm2.bsp');
    Q3Node := nil;

    // The Quake mesh is pickable, but doesn't get highlighted.
    if Assigned(Q3levelmesh) then
    begin
      Q3Node := Smgr.AddOctreeSceneNode(Q3levelmesh.GetMesh(0), nil, Ord(IDFlag_IsPickable));
    end;

    (*
    So far so good, we've loaded the quake 3 level like in tutorial 2. Now,
    here comes something different: We create a triangle selector. A
    triangle selector is a class which can fetch the triangles from scene
    nodes for doing different things with them, for example collision
    detection. There are different triangle selectors, and all can be
    created with the ISceneManager. In this example, we create an
    OctreeTriangleSelector, which optimizes the triangle output a little
    bit by reducing it like an octree. This is very useful for huge meshes
    like quake 3 levels. After we created the triangle selector, we attach
    it to the Q3Node. This is not necessary, but in this way, we do not
    need to care for the selector, for example dropping it after we do not
    need it anymore.
  	*)
    Selector := nil;
    if Assigned(Q3Node) then
    begin
      Q3Node.SetPosition(Vector3DF(-1350, -130, -1400));

      Selector := Smgr.CreateOctreeTriangleSelector(
        Q3Node.GetMesh, Q3Node, 128);
      Q3Node.SetTriangleSelector(Selector);
      // We're not done with this selector yet, so don't drop it.
    end;

    (*
    We add a first person shooter camera to the scene so that we can see and
    move in the quake 3 level like in tutorial 2. But this, time, we add a
    special animator to the camera: A Collision Response animator. This
    animator modifies the scene node to which it is attached to in order to
    prevent it moving through walls, and to add gravity to it. The
    only thing we have to tell the animator is how the world looks like,
    how big the scene node is, how much gravity to apply and so on. After the
    collision response animator is attached to the camera, we do not have to do
    anything more for collision detection, anything is done automatically.
    The rest of the collision detection code below is for picking. And please
    note another cool feature: The collision response animator can be
    attached also to all other scene nodes, not only to cameras. And it can
    be mixed with other scene node animators. In this way, collision
    detection and response in the Irrlicht engine is really easy.

    Now we'll take a closer look on the parameters of
    createCollisionResponseAnimator(). The first parameter is the
    TriangleSelector, which specifies how the world, against collision
    detection is done looks like. The second parameter is the scene node,
    which is the object, which is affected by collision detection, in our
    case it is the camera. The third defines how big the object is, it is
    the radius of an ellipsoid. Try it out and change the radius to smaller
    values, the camera will be able to move closer to walls after this. The
    next parameter is the direction and speed of gravity.  We'll set it to
    (0, -10, 0), which approximates to realistic gravity, assuming that our
    units are metres. You could set it to (0,0,0) to disable gravity. And the
    last value is just a translation: Without this, the ellipsoid with which
    collision detection is done would be around the camera, and the camera would
    be in the middle of the ellipsoid. But as human beings, we are used to have our
    eyes on top of the body, with which we collide with our world, not in
    the middle of it. So we place the scene node 50 units over the center
    of the ellipsoid with this parameter. And that's it, collision
    detection works now.
    *)

	  // Set a jump speed of 3 units per second, which gives a fairly realistic jump
  	// when used with the gravity of (0, -10, 0) in the collision response animator.
    Camera := Smgr.AddCameraSceneNodeFPS(nil, 100, 0.3, ID_IsNotPickable, nil, 0, True, 3);
    Camera.SetPosition(Vector3DF(50, 50, -60));
    Camera.SetTarget(Vector3DF(-70, 30, -60));

    if Assigned(selector) then
    begin
      Anim := Smgr.CreateCollisionResponseAnimator(
        Selector, Camera, Vector3DF(30, 50, 30),
        Vector3DF(0, -10, 0), Vector3DF(0, 30, 0));
      Selector.Drop;       // As soon as we're done with the selector, drop it.
      Camera.AddAnimator(anim);
      Anim.Drop;           // And likewise, drop the animator when we're done referring to it.
    end;

    // Now I create three animated characters which we can pick, a dynamic light for
    // lighting them, and a billboard for drawing where we found an intersection.

    // First, let's get rid of the mouse cursor.  We'll use a billboard to show
    // what we're looking at.
    Device.GetCursorControl.SetVisible(False);

    // Add the billboard.
    Bill := Smgr.AddBillboardSceneNode;
    Bill.SetMaterialType(EMT_TRANSPARENT_ADD_COLOR);
    Bill.SetMaterialTexture(0, Driver.GetTexture('..\..\media\particle.bmp'));
    Bill.SetMaterialFlag(EMF_LIGHTING, False);
    Bill.SetMaterialFlag(EMF_ZBUFFER, False);
    Bill.SetSize(Dimension2DF(20, 20));
    Bill.SetID(ID_IsNotPickable);        // This ensures that we don't accidentally ray-pick it

    (* Add 3 animated hominids, which we can pick using a ray-triangle intersection.
    They all animate quite slowly, to make it easier to see that accurate triangle
    selection is being performed. *)
    //Node := nil;

    // Add an MD2 node, which uses vertex-based animation.
    Node := Smgr.AddAnimatedMeshSceneNode
            (
              Smgr.GetMesh('..\..\media\faerie.md2'),
              nil,
              IDFlag_IsPickable or IDFlag_IsHighlightable
            );

    Node.SetPosition(Vector3DF(-90, -15, -140));      // Put its feet on the floor.
    Node.SetScale(Vector3DF(1.6));                    // Make it appear realistically scaled
    Node.SetMD2Animation(EMAT_POINT);
    Node.SetAnimationSpeed(20);

    Material.Init;
    Material.SetTexture(0, Driver.GetTexture('..\..\media\faerie2.bmp'));
    Material.Lighting := True;
    Material.NormalizeNormals := True;
    MaterialPtr := Node.GetMaterial(0);
    MaterialPtr^.Clone(Material);

    // Now create a triangle selector for it.  The selector will know that it
    // is associated with an animated node, and will update itself as necessary.
    Selector := Smgr.CreateTriangleSelector(Node);
    Node.SetTriangleSelector(Selector);
    Selector.Drop;           // We're done with this selector, so drop it now.

    // And this B3D file uses skinned skeletal animation.
    Node := Smgr.AddAnimatedMeshSceneNode(Smgr.GetMesh('..\..\media\ninja.b3d'),
      nil, IDFlag_IsPickable or IDFlag_IsHighlightable);
    Node.SetScale(Vector3DF(10));
    Node.SetPosition(Vector3DF(-75, -66, -80));
    Node.SetRotation(Vector3DF(0, 90, 0));
    Node.SetAnimationSpeed(8);
    Node.GetMaterial(0)^.NormalizeNormals := True;
    Node.GetMaterial(0)^.Lighting := True;
    // Just do the same as we did above.
    Selector := Smgr.CreateTriangleSelector(Node);
    Node.SetTriangleSelector(Selector);
    Selector.Drop;

    // This X files uses skeletal animation, but without skinning.
    Node := Smgr.AddAnimatedMeshSceneNode(Smgr.GetMesh('..\..\media\dwarf.x'),
      nil, IDFlag_IsPickable or IDFlag_IsHighlightable);
    Node.SetPosition(Vector3DF(-70, -66, -30));    // Put its feet on the floor.
    Node.SetRotation(Vector3DF(0, -90, 0));        // And turn it towards the camera.
    Node.SetAnimationSpeed(20);
    Node.GetMaterial(0)^.Lighting := True;
    Selector := Smgr.CreateTriangleSelector(Node);
    Node.SetTriangleSelector(Selector);
    Selector.Drop;

    // And this mdl file uses skinned skeletal animation.
    Node := Smgr.AddAnimatedMeshSceneNode(Smgr.GetMesh('..\..\media\yodan.mdl'),
      nil, IDFlag_IsPickable or IDFlag_IsHighlightable);
    Node.SetPosition(Vector3DF(-90, -25, 20));
    Node.SetScale(Vector3DF(0.8));
    Node.GetMaterial(0)^.Lighting := True;
    Node.SetAnimationSpeed(20);

    // Just do the same as we did above.
    Selector := Smgr.CreateTriangleSelector(Node);
    Node.SetTriangleSelector(Selector);
    Selector.Drop;

    Material.SetTexture(0, nil);
    Material.Lighting := False;

    // Add a light, so that the unselected nodes aren't completely dark.
    Light := Smgr.AddLightSceneNode(nil, Vector3DF(-60, 100, 400),
      IrrColorF(1, 1, 1, 1), 600);
    Light.SetID(ID_IsNotPickable);    // Make it an invalid target for selection.

    // Remember which scene node is highlighted
    HighlightedSceneNode := nil;
    CollMan := Smgr.GetSceneCollisionManager;
    LastFPS := -1;

    // draw the selection triangle only as wireframe
    Material.Wireframe := True;

    while (Device.Run and Assigned(Driver)) do
    begin
      if Device.IsWindowActive then
      begin
        Driver.BeginScene(True, True, IrrColor(0, 200, 200, 200));

        Smgr.DrawAll;

        // Unlight any currently highlighted scene node
        if Assigned(HighlightedSceneNode) then
        begin
          HighlightedSceneNode.SetMaterialFlag(EMF_LIGHTING, True);
          HighlightedSceneNode := nil;
        end;

        // All intersections in this example are done with a ray cast out from the camera to
        // a distance of 1000.  You can easily modify this to check (e.g.) a bullet
        // trajectory or a sword's position, or create a ray from a mouse click position using
        // ISceneCollisionManager::getRayFromScreenCoordinates()
        Ray.StartPos := Camera.GetPosition^;
        TmpVec := Camera.GetTarget^ - Ray.StartPos;
        TmpVec.Normalize;
        Ray.EndPos := Ray.StartPos + TmpVec * 1000;


        // This call is all you need to perform ray/triangle collision on every scene node
        // that has a triangle selector, including the Quake level mesh.  It finds the nearest
        // collision point/triangle, and returns the scene node containing that point.
        // Irrlicht provides other types of selection, including ray/triangle selector,
        // ray/box and ellipse/triangle selector, plus associated helpers.
        // See the methods of ISceneCollisionManager
        SelectedSceneNode := CollMan.GetSceneNodeAndCollisionPointFromRay(
          Ray,
          InterSection,         // This will be the position of the collision
          HitTriangle,          // This will be the triangle hit in the collision
          IDFlag_IsPickable,    // This ensures that only nodes that we have set up to be pickable are considered
          nil                   // Check the entire scene (this is actually the implicit default)
          );

        // If the ray hit anything, move the billboard to the collision position
        // and draw the triangle that was hit.
        if Assigned(SelectedSceneNode) then
        begin
          if Assigned(Bill) then
            Bill.SetPosition(InterSection);

          // We need to reset the transform before doing our own rendering.
          Matrix4.Init;
          Driver.SetTransform(ETS_WORLD, Matrix4);
          Driver.SetMaterial(Material);
          Driver.Draw3DTriangle(HitTriangle, IrrColor(0, 255, 0, 0));

          // We can check the flags for the scene node that was hit to see if it should be
          // highlighted. The animated nodes can be highlighted, but not the Quake level mesh
          if (SelectedSceneNode.GetID and IDFlag_IsHighlightable) = IDFlag_IsHighlightable then
          begin
            HighlightedSceneNode := SelectedSceneNode;

            // Highlighting in this case means turning lighting OFF for this node,
            // which means that it will be drawn with full brightness.
            HighlightedSceneNode.SetMaterialFlag(EMF_LIGHTING, False);
          end;
        end;

        // We're all done drawing, so end the scene.
        Driver.EndScene;

        FPS := Driver.GetFPS;
        if (LastFPS <> FPS) then
        begin
          S := 'Collision detection example - Irrlicht Engine [' + String(Driver.GetName)
            + '] FPS:' + IntToStr(FPS);

          Device.SetWindowCaption(PWideChar(S));
          LastFPS := FPS;
        end;

      end;
    end;

    Device.Drop;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
